<!--
  * 忘记密码
-->
<template>
  <div class="login-container">
    <div class="box-item login" v-if="!rPw">
      <div class="text-2xl mb-3">
        <a-button type="link" style="padding: 0 0.5em 0 0" class="text-2xl" @click="goTo('/login')"
          ><ArrowLeftOutlined class="text-gray-500" /></a-button
        >输入验证码
      </div>
      <a-form ref="formRef" class="login-form" :model="loginForm" :rules="rules">
        <a-form-item name="userType">
          <a-select v-model:value="loginForm.userType" size="large">
            <a-select-option v-for="item in ZZB_USER_TYPE_ENUM" :key="item.value" :value="item.value">
              {{ item.desc }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name="loginName">
          <a-input type="text" v-model:value.trim="loginForm.loginName" placeholder="请输入用户名" />
        </a-form-item>
        <!-- <a-form-item name="emailCode" v-if="emailCodeShowFlag">
          <a-input-group compact>
            <a-input style="width: calc(100% - 110px)" v-model:value="loginForm.emailCode" autocomplete="on" placeholder="请输入邮箱验证码" />
            <a-button @click="sendSmsCode" class="code-btn" type="primary" :disabled="emailCodeButtonDisabled">
              {{ emailCodeTips }}
            </a-button>
          </a-input-group>
        </a-form-item> -->
        <!-- <a-form-item name="password">
          <a-input-password
            v-model:value="loginForm.newPassword"
            autocomplete="on"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码：至少三种字符，最小 8 位"
          />
        </a-form-item> -->
        <a-form-item name="sum">
          <a-input class="captcha-input" v-model:value.trim="loginForm.sum" placeholder="请输入验证码" />
          <img class="captcha-img" :src="captchaBase64Image" @click="getCaptcha" />
        </a-form-item>

        <a-form-item>
          <a-flex justify="space-between" align="center" class="text-sm text-slate-500">
            <div>
              <a-button class="text-sm" type="link" :disabled="remainingTime > 0" @click="textingFn">获取短信验证码</a-button>
              <span>验证码有效期90秒</span>
            </div>
            <div v-if="remainingTime > 0">倒计时{{ timeval }}</div>
          </a-flex>
        </a-form-item>
        <a-form-item name="code">
          <a-input type="text" v-model:value.trim="loginForm.code" placeholder="请输入短信验证码" />
        </a-form-item>
        <a-form-item>
          <a-button @click="onLogin" type="primary" class="w-full" size="large">确认</a-button>
        </a-form-item>
      </a-form>
    </div>

    <div class="box-item login" v-else>
      <div class="text-2xl mb-3 text-center">设置密码</div>
      <a-form ref="formRefPwd" class="login-form" :model="rPwdForm" :rules="rulesPw">
        <a-form-item name="loginName">
          <a-input type="text" v-model:value.trim="rPwdForm.loginName" :maxlength="20" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item name="newPassword">
          <a-input-password
            v-model:value="rPwdForm.newPassword"
            autocomplete="on"
            :maxlength="20"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码：至少三种字符，最小 8 位"
          />
        </a-form-item>
        <a-form-item name="newPasswordAgain">
          <a-input-password
            v-model:value="rPwdForm.newPasswordAgain"
            autocomplete="on"
            :maxlength="20"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入新密码"
          />
        </a-form-item>
        <a-form-item>
          <a-button @click="ok" type="primary" class="w-full" size="large">确认</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script setup>
  import { message } from 'ant-design-vue'
  import { onMounted, onUnmounted, reactive, ref, computed, watch } from 'vue'
  import { useRouter } from 'vue-router'
  import { loginApi } from '/@/api/system/b-auth/login-api'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { localSave } from '/@/utils/local-util.js'
  import LocalStorageKeyConst from '/@/constants/local-storage-key-const.js'
  import { ZZB_USER_TYPE_ENUM } from '/@/constants/system/system-const.js'
  import { formatTime } from '/@/utils/common'
  import { isMulPassword } from '/@/utils/validate'
  import { isEmpty, cloneDeep } from 'lodash'

  const rPw = ref(false)
  //--------------------- 登录表单 ---------------------------------
  const infoForm = {
    userType: ZZB_USER_TYPE_ENUM.USER_TYPE_PLATFORM.value,
    loginName: undefined,
    newPassword: undefined,
    newPasswordAgain: undefined,
    sum: undefined,
    code: undefined,
    captchaUuid: undefined,
    token: undefined,
  }
  // 判断点击的按钮
  const loginForm = reactive(cloneDeep(infoForm))
  const rules = {
    loginName: [{ required: true, message: '用户名不能为空' }],
    // sum: [{ required: true, message: '验证码不能为空' }],
    code: [
      {
        required: true,
        message: '短信验证码不能为空',
      },
    ],
  }

  const rPwdForm = ref(cloneDeep(infoForm))
  const rulesPw = ref({
    userType: [{ required: true, message: '用户类型不能为空' }],
    loginName: [{ required: true, message: '用户名不能为空' }],
    newPassword: [
      { required: true, message: '密码不能为空' },
      {
        validator: isMulPassword,
      },
    ],
    newPasswordAgain: [
      { required: true, message: '密码不能为空' },
      {
        validator: isMulPassword,
      },
    ],
  })

  const showPassword = ref(false)
  const router = useRouter()
  const formRef = ref()
  const formRefPwd = ref()

  onMounted(() => {
    // document.onkeyup = (e) => {
    //   if (e.keyCode === 13) {
    //     onLogin()
    //   }
    // }
  })

  onUnmounted(() => {
    document.onkeyup = null
  })

  /* 倒计时 */
  const TIME = 90
  const remainingTime = ref(0)
  const timer = ref(null) //定时器
  const timeval = computed(() => {
    let val = 0
    if (Number(remainingTime.value) >= 0) {
      val = formatTime(remainingTime.value)
    }
    return val
  })
  function startCountdown() {
    remainingTime.value = TIME
    timer.value = setInterval(() => {
      if (remainingTime.value > 0) {
        remainingTime.value--
      } else {
        clearInterval(timer.value)
      }
    }, 1000)
  }
  /*  */
  /* 短信验证码 */
  const textingFn = async () => {
    if (isEmpty(loginForm.loginName) || isEmpty(loginForm.sum)) {
      return message.warning('用户名和验证码不能为空')
    }
    try {
      SmartLoading.show()
      const res = await loginApi.getSmsCode(loginForm)
      // stopRefreshCaptchaInterval()
      message.success('发送验证码成功')
      startCountdown()
    } catch (e) {
      if (e.data && e.data.code !== 0) {
        loginForm.sum = ''
        getCaptcha()
      }
      console.log(e)
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }
  /* 短信验证码 */

  //确认发送短信getSmsCode、verifySmsCode
  async function onLogin() {
    formRef.value.validate().then(async () => {
      try {
        SmartLoading.show()
        const res = await loginApi.verifySmsCode(loginForm)
        stopRefreshCaptchaInterval()
        message.success('请修改密码')
        rPw.value = true
        rPwdForm.value.loginName = loginForm.loginName
        rPwdForm.value.userType = loginForm.userType
        rPwdForm.value.token = res.data.token
      } catch (e) {
        console.log(e)
        smartSentry.captureError(e)
      } finally {
        SmartLoading.hide()
      }
    })
  }
  //确认修改密码
  async function ok() {
    formRefPwd.value.validate().then(async () => {
      try {
        if (rPwdForm.value.newPasswordAgain !== rPwdForm.value.newPassword) {
          message.error('新密码与确认密码不一致')
          return
        }
        SmartLoading.show()
        const res = await loginApi.resetPassword(rPwdForm.value)
        if (res.code !== 200) {
          message.error(res.message)
          return
        }
        message.success('修改成功')
        router.push('/login')
      } catch (e) {
        console.log(e)

        smartSentry.captureError(e)
      } finally {
        SmartLoading.hide()
      }
    })
  }

  //--------------------- 验证码 ---------------------------------

  const captchaBase64Image = ref('')

  async function getCaptcha() {
    localSave(LocalStorageKeyConst.USER_TYPE, loginForm.userType ? loginForm.userType : ZZB_USER_TYPE_ENUM.USER_TYPE_PLATFORM.value)

    try {
      let captchaResult = await loginApi.getCaptcha()
      captchaBase64Image.value = captchaResult.data.captchaBase64Image
      loginForm.captchaUuid = captchaResult.data.captchaUuid
      beginRefreshCaptchaInterval(captchaResult.data.captchaExpireTime)
    } catch (e) {
      console.log('e==>', e)
    }
  }

  let refreshCaptchaInterval = null

  function beginRefreshCaptchaInterval(expireSeconds = 6) {
    if (refreshCaptchaInterval === null) {
      refreshCaptchaInterval = setInterval(getCaptcha, (expireSeconds - 5) * 1000)
    }
  }
  function stopRefreshCaptchaInterval() {
    if (refreshCaptchaInterval != null) {
      clearInterval(refreshCaptchaInterval)
      refreshCaptchaInterval = null
    }
  }

  onMounted(() => {
    getCaptcha()
  })
  watch(
    () => loginForm.userType,
    () => {
      getCaptcha()
    },
  )

  function goTo(url, data) {
    router.push({ path: url, query: data })
  }
</script>
<style lang="less" scoped>
  @import './login.less';
  .login-container .box-item.login {
    border-radius: 12px;
  }
</style>
